package cn.tedu.charging.order.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * EMQX的消息中间件的 发送者
 * 订单服务给设备发送 消息(指令)
 */

@Slf4j
@Component
public class MqttProducer {
    @Autowired
    private MqttClient mqttClient;

//    public void send(String topic,String message) throws Exception{
//        mqttClient.publish(topic,message.getBytes(),0,false);
//    }

    public Boolean send(String topic, String message) {
        Boolean success = true;
        try {
            mqttClient.publish(topic, message.getBytes(), 0, false);
            success = true;
        } catch (MqttException e) {
//            throw new RuntimeException(e);
            //接入告警系统,1秒超过3次失败 告警
            log.error("给EMQX发送消息失败,topic:{},消息:{}", topic, message, e);
            success = false;
        }
        return success;
    }

}
